package cn.cyh.queue_service.mapper;

import cn.cyh.queue_service.model.entity.Queue;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

/**
 * 队列Mapper接口
 */
@Mapper
public interface QueueMapper extends BaseMapper<Queue> {
    
    /**
     * 根据业务类型获取等待中的队列列表，按取号时间排序
     * 
     * @param serviceTypeId 业务类型ID
     * @return 队列列表
     */
    @Select("SELECT * FROM biz_queue WHERE service_type_id = #{serviceTypeId} AND status = 'WAITING' ORDER BY create_time ASC")
    List<Queue> selectWaitingQueuesByServiceType(@Param("serviceTypeId") Long serviceTypeId);
    
    /**
     * 获取指定票号的队列记录
     * 
     * @param ticketNumber 票号
     * @return 队列记录
     */
    @Select("SELECT * FROM biz_queue WHERE ticket_number = #{ticketNumber} order by id desc  LIMIT 1")
    Queue selectByTicketNumber(@Param("ticketNumber") String ticketNumber);
    
    /**
     * 更新队列状态
     * 
     * @param queueId 队列ID
     * @param status 状态
     * @return 更新影响行数
     */
    @Update("UPDATE biz_queue SET status = #{status} WHERE id = #{queueId}")
    int updateStatus(@Param("queueId") Long queueId, @Param("status") String status);
    
    /**
     * 获取指定窗口当前服务的队列记录
     * 
     * @param windowId 窗口ID
     * @return 队列记录
     */
    @Select("SELECT * FROM biz_queue WHERE window_id = #{windowId} AND status IN ('CALLING', 'SERVING') LIMIT 1")
    Queue selectCurrentQueueByWindow(@Param("windowId") Long windowId);
    
    /**
     * 统计指定业务类型的等待人数
     * 
     * @param serviceTypeId 业务类型ID
     * @return 等待人数
     */
    @Select("SELECT COUNT(*) FROM biz_queue WHERE service_type_id = #{serviceTypeId} AND status = 'WAITING'")
    int countWaitingByServiceType(@Param("serviceTypeId") Long serviceTypeId);
    
    /**
     * 获取当日指定业务类型的最大票号
     * 
     * @param serviceTypeId 业务类型ID
     * @param prefix 前缀
     * @return 最大票号
     */
    @Select("SELECT ticket_number FROM biz_queue WHERE service_type_id = #{serviceTypeId} AND ticket_number LIKE CONCAT(#{prefix}, '%') AND DATE(create_time) = CURDATE() ORDER BY id DESC LIMIT 1")
    String selectMaxTicketNumberToday(@Param("serviceTypeId") Long serviceTypeId, @Param("prefix") String prefix);
} 